﻿using Castle.DynamicProxy;
using PlutoStudio.Aspects;
using PlutoStudio.Dependency;
using System;
using System.Collections.Generic;
using System.Text;

namespace PlutoStudio.Runtime.Validation.Interception
{
    public class ValidationInterceptor : IInterceptor
    {
        private readonly IIocResolver _iocResolver;

        public ValidationInterceptor(IIocResolver iocResolver)
        {
            _iocResolver = iocResolver;
        }

        public void Intercept(IInvocation invocation)
        {
            if (CrossCuttingConcerns.IsApplied(invocation.InvocationTarget, CrossCuttingConcerns.Validation))
            {
                invocation.Proceed();
                return;
            }

            using (var validator = _iocResolver.ResolveAsDisposable<MethodInvocationValidator>())
            {
                validator.Value.Initialize(invocation.MethodInvocationTarget, invocation.Arguments);
                validator.Value.Validate();
            }

            invocation.Proceed();
        }
    }
}
